package com.mical.demo.service;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenBlacklistService {
    private static final String BLACKLIST_PREFIX = "jwt:blacklist:";

    @Autowired
@Qualifier("df1")
    private RedisTemplate<String, Object> redisTemplate;

    // 加入黑名单（带TTL）
    public void addToBlacklist(String token, long remainingMillis) {
        String hashedToken = hashToken(token);
        redisTemplate.opsForValue().set(
                BLACKLIST_PREFIX + hashedToken,
                "invalid",
                remainingMillis,
                TimeUnit.MILLISECONDS
        );
    }

    // 检查是否在黑名单中
    public boolean isBlacklisted(String token) {
        String hashedToken = hashToken(token);
        return Boolean.TRUE.equals(redisTemplate.hasKey(BLACKLIST_PREFIX + hashedToken));
    }

    // Token哈希处理（安全存储）
    private String hashToken(String token) {
        return DigestUtils.sha256Hex(token);
    }
}